package com.geek.gkpush.framework.event.model;

import com.geek.gkpush.util.excp.ExcpStackUtils;
import com.geek.gkpush.util.excp.GkPushCodeEnum;
import com.geek.gkpush.util.excp.GkPushException;
import com.geek.gkpush.util.json.JacksonUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.Serializable;

/**
 * <h1>事件消息执行的结果。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2023/10/2
 *
 */
@Setter
@Getter
@ToString(callSuper = true)
public class EventResult implements Serializable {

    private static final long serialVersionUID = -9133366004013606150L;

    private String resultCode;
    private String resultMsg;

    /**
     * <h2>判断结果是否成功，true-返回成功；false-返回失败。</h2>
     *
     * @return
     */
    public boolean toSuccFlag() {
        return GkPushCodeEnum.isSucc(this.resultCode);
    }

    /**
     * <h2>得到成功的转换结果。</h2>
     *
     * @return
     */
    public static EventResult toSuccResult() {
        EventResult result = new EventResult();

        result.setResultCode(GkPushCodeEnum.SUCCESS.getCode());
        result.setResultMsg(GkPushCodeEnum.SUCCESS.getMsg());

        return result;
    }

    /**
     * <h2>将异常转换为当前对象。</h2>
     *
     * @param e
     * @return
     */
    public static EventResult toExceptionResult(Exception e) {
        EventResult result = new EventResult();
        if (e instanceof GkPushException) {
            GkPushException excp = (GkPushException) e;
            result.setResultCode(excp.getExcpCode());
            result.setResultMsg(String.join("_", excp.getExcpCode(),
                    ExcpStackUtils.getStackTrace(e)));
            return result;
        }

        result.setResultCode(GkPushCodeEnum.SYSTEM_EXCEPTION.getCode());
        result.setResultMsg(String.join("_",
                GkPushCodeEnum.SYSTEM_EXCEPTION.getCode(), ExcpStackUtils.getStackTrace(e)));

        return result;
    }

    /**
     * <h2>将当前对象转换为 JSON 字符串。</h2>
     *
     * @param:
     * @return: java.lang.String
     */
    public String toJson() {
        return JacksonUtils.toJson(this);
    }
}